package com.client.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;

@Component
//AES加解密工具类--CTR
public class AESutil {


    static {
        try {
            Security.addProvider(new BouncyCastleProvider());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static final String KEY_ALGORITHM = "AES";
    public static final String CIPHER_ALGORITHM = "AES/CTR/PKCS5Padding";
    public static final String ivParameter = "1234123412341234";

    public static byte[] encrypt(byte[] msg, byte[] key) {
        try {
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            SecretKeySpec sKeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, iv);
            return cipher.doFinal(msg);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] decrypt(byte[] msg, byte[] key) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            return cipher.doFinal(msg);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    public static byte[] decode(byte[] msg, byte[] key) {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(key, KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            return cipher.doFinal(msg);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
